//
//  UISingleLeadECGView.m
//  ECGDemo
//
//  Created by jia yu on 2021/12/24.
//

#import "UIECGSingleReView.h"


@interface UIECGSingleReView(){
    CAShapeLayer *ecgLayer;
}
@end

@implementation UIECGSingleReView
@synthesize pixPermm;
@synthesize ecgsArray;
@synthesize speedX,rateY;
@synthesize rateECG;
@synthesize lineWidth,lineColor;
@synthesize lineSpace;


-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        pixPermm = 6.2f;
        ecgsArray = [[NSMutableArray alloc] init];
        speedX = 25.f;
        rateY = 10.f;
        rateECG = 512.f;
        lineWidth = 2.f;
        lineColor = [UIColor colorWithRed:0.2 green:0.21 blue:0.21 alpha:1.f];
        lineSpace = 15.f;
    }
    return self;
}

-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    [self drawECG];
}


-(void)drawECG{
    if (ecgLayer){
        [ecgLayer removeFromSuperlayer];
    }
    
    float seekPerPoint = speedX * pixPermm/rateECG;
    float currentX = 0.f;
    float currentMiddle = lineSpace * pixPermm;
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, currentX, currentMiddle);
    currentX += 1.5f * pixPermm;
    CGPathAddLineToPoint(path, NULL, currentX, currentMiddle);
    CGPathAddLineToPoint(path, NULL, currentX, currentMiddle - rateY * pixPermm);
    currentX += 2.f * pixPermm;
    CGPathAddLineToPoint(path, NULL, currentX, currentMiddle - rateY * pixPermm);
    CGPathAddLineToPoint(path, NULL, currentX, currentMiddle);
    currentX += 1.5f * pixPermm;
    CGPathAddLineToPoint(path, NULL, currentX, currentMiddle);
    CGPathMoveToPoint(path, NULL, -1.f, -1.f);
    CGPathCloseSubpath(path);
    
    
    BOOL isPenDown = NO;
    for (NSNumber *n in ecgsArray){
        float y = currentMiddle - pixPermm * 10.f * [n floatValue] / 1000.f;
        if (isPenDown){
            CGPathAddLineToPoint(path, NULL, currentX, y);
        }else{
            isPenDown = YES;
            CGPathMoveToPoint(path, NULL, currentX, y);
        }
        currentX += seekPerPoint;
        if (currentX >= self.frame.size.width){
            CGPathMoveToPoint(path, NULL, -1.f, -1.f);
            CGPathCloseSubpath(path);
            CGPathMoveToPoint(path, NULL, -1.f, -1.f);
            currentX = 0.f;
            currentMiddle += lineSpace * pixPermm;
            isPenDown = NO;
        }
    }
    
    ecgLayer = [CAShapeLayer layer];
    ecgLayer.path = path;
    ecgLayer.lineWidth = lineWidth;
    ecgLayer.strokeColor = lineColor.CGColor;
    ecgLayer.fillColor = [UIColor clearColor].CGColor;
    [self.layer addSublayer:ecgLayer];
    
    CGPathRelease(path);
}

@end
